package net.jsoft.platform.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;

public class CustomUserDetailsService implements UserDetailsService
{
    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException
    {
        //SUser对应数据库中的用户表，是最终存储用户和密码的表，可自定义
        //本例使用SUser中的email作为用户名:
        SysUser u = repository.findByName(userName);
        if (u == null)
        {
            throw new UsernameNotFoundException("UserName " + userName + " not found");
        }

        // SecurityUser实现UserDetails并将SUser的Email映射为username
        //        SecurityUser user = new SecurityUser(u);
        //        Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        //        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        //        for (SysRole r : u.getSysRoles())
        //        {
        //            authorities.add(new SimpleGrantedAuthority(r.getName()));
        //        }
        //        System.out.println("username:" + user.getUsername() + ";password:" + user.getPassword());
        return u;

    }

}
